package com.zxisl.util;

import com.zxisl.bean.Mail;
import com.zxisl.init.Init;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.util.*;

/**
 * Created by ade on 2016/11/3.
 */
public class XpathUtil {


    public static Logger xpathUtilLogger = Logger.getLogger(XpathUtil.class);

    /**
     * 获取mail
     *
     * @return
     */
    public static Map<String, Mail> getMailByXpath() {
        Map<String, Mail> mailMap = new HashMap<String, Mail>();
        String[] userInfo = new String[2];
        List<Mail> mailList = null;
        try {
            mailList = Init.getMailListByXpath(userInfo);
        } catch (DocumentException e) {
            xpathUtilLogger.info(e.getMessage());
            return mailMap;
        }
        for (Mail mail : mailList) {
            mailMap.put(mail.getHost(), mail);
        }
        return mailMap;
    }


    /**
     * 遍历当前节点元素下面的所有(元素的)子节点
     *
     * @param node
     */
    public static List<String> getListNodes(Element node) {
        List<String> subList = new ArrayList<String>();
        System.out.println("getListNodes " + " 当前节点的名称：：" + node.getName());
        // 当前节点下面子节点迭代器
        Iterator<Element> it = node.elementIterator();
        // 遍历
        while (it.hasNext()) {
            // 获取某个子节点对象
            Element e = it.next();
            // 对子节点进行遍历
            subList.add(e.getText());
        }
        return subList;
    }

    /**
     * 遍历当前节点元素下面的所有(元素的)子节点
     *
     * @param node
     */
    public static void listNodes(Element node) {
        System.out.println("当前节点的名称：：" + node.getName());
        // 获取当前节点的所有属性节点
        List<Attribute> list = node.attributes();
        // 遍历属性节点
        for (Attribute attr : list) {
            System.out.println(attr.getText() + "-----" + attr.getName()
                    + "---" + attr.getValue());
        }
        if (!(node.getTextTrim().equals(""))) {
            System.out.println("文本内容：：：：" + node.getText());
        }

        // 当前节点下面子节点迭代器
        Iterator<Element> it = node.elementIterator();
        // 遍历
        while (it.hasNext()) {
            // 获取某个子节点对象
            Element e = it.next();
            // 对子节点进行遍历
            listNodes(e);
        }
    }
}
